//
//  SYJComposeViewController.swift
//  weibo
//
//  Created by 孙英建 on 16/4/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class SYJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        setUpUI()
    }
    
    
    // 设置UI控件
    func setUpUI(){
        self.view.backgroundColor = UIColor.whiteColor()
        
        // 设置导航栏
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelItem")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendItem")
        
        // 设置发送起始为禁用
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        // 标题视图
        navigationItem.titleView = titleView
        
        
        // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composePickerView)
        view.addSubview(composeToolBar)
        
        // 添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        composePickerView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(10)
            make.width.height.equalTo(kWidth - 20)
            make.top.equalTo(composeTextView).offset(220)
        }
        
        
        
        // 监听toolBar按钮的点击
        composeToolBar.composeToolBarClosure = {[weak self](tag: Int) in
            
            switch tag {
            case 1:
                self?.selectImage()
            case 2:
                print("@")
            case 3:
                print("#")
            case 4:
                self?.switchKeyborad()
            case 5:
                print("+")
            default:
                break
            }
        }
        
        // 点击加号弹出相册的闭包赋值
        composePickerView.composePickerViewClosure = {[weak self] in
            self?.selectImage()
        }
        
        // 监听键盘的弹出frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // MARK: - 各种事件
    // 键盘弹出的通知的事件
    func keyboardWillChangeFrame(noti: NSNotification){
        // 获取键盘弹出的frame
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()

        // 修改底部视图的约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
             make.bottom.equalTo(view).offset(rect.origin.y - kHeight)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    // 取消item的点击事件
    @objc private func cancelItem(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 发送item的点击事件
    @objc private func sendItem(){
        print("发送按钮背点击了")
    }
    
    
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        let name = SYJUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        let titleStr = "发微博\n\(name)"
        
        // 富文本
        let attr = NSMutableAttributedString(string: titleStr)
        let range = (titleStr as NSString).rangeOfString(name)
        
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: range)
        
        let lab = UILabel()
        lab.font = UIFont.systemFontOfSize(17)
        lab.textColor = UIColor.darkGrayColor()
        
        lab.attributedText = attr
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        
        lab.sizeToFit()
        
        return lab
    }()
    
    // 文本输入框
    private lazy var composeTextView: SYJComposeTextView = {
       let ctv = SYJComposeTextView()
        ctv.font = UIFont.systemFontOfSize(16)
        ctv.placeholderStr = "大家好我是占位符大家好我是占位符大家好我是占位符大家好我是占位符大家好我是占位符大家好我是占位符"
        ctv.delegate = self
//        ctv.alwaysBounceVertical = true
        return ctv
    }()
    
    // 底部toolBar
    private lazy var composeToolBar: SYJComposeToolBar = SYJComposeToolBar()
    
    // 配图
    private lazy var composePickerView: SYJComposePickerView = SYJComposePickerView()
    
    // 自定义表情键盘
    private lazy var emoticonKeyboard: SYJEmoticonKeyboardView = {
       let emoticon = SYJEmoticonKeyboardView()
        emoticon.frame = CGRect(x: 0, y: 0, width: kWidth, height: 216)
        return emoticon
    }()
    
}

// MARK: - composeTextView的代理方法
extension SYJComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}


// MARK: - 处理ToolBar里边的按钮的点击逻辑
extension SYJComposeViewController{
    
    // 点击调用相册
    func selectImage(){
        let pickerVc = UIImagePickerController()

        pickerVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            // 相机
            
        }else{
            // 相册
            presentViewController(pickerVc, animated: true, completion: nil)
        }
    }
    
    
    // 表情键盘的切换
    func switchKeyborad(){
        if composeTextView.inputView == nil{
            // 如果inputView为nil代表当前为系统键盘 将其切换为表情键盘 让其显示系统键盘图标
            composeTextView.inputView = emoticonKeyboard
            composeToolBar.isEmoticon = true
        }else{
            // 否则代表当前为表情键盘 将其切换为系统键盘 让其显示表情键盘图标
            composeTextView.inputView = nil
            composeToolBar.isEmoticon = false
        }
        
        // 刷新
        composeTextView.reloadInputViews()
        // 点击后让其成为第一响应者弹出键盘
        composeTextView.becomeFirstResponder()
    }
    
    
    
}

// MARK: - 保存相册图片
extension SYJComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePickerView.addImageToImageArr(getImageScale(image, width: 600))
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    // 利用图片上下文压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
        // 如果我们的图片宽度小于我们制定的宽度我们直接返回 不处理
        if image.size.width < width{
            return image
        }

        let height = (image.size.height * width) / image.size.width
        
         UIGraphicsBeginImageContext(CGSize(width: width, height: height))

        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))

        let result = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return result
    }

    
}













